package main

import (
	"flag"
	"fmt"
	"github.com/Caisin/sfile/utils/ftp"
	"github.com/Caisin/sfile/utils/sfile"
	"github.com/Caisin/sfile/utils/timeUtil"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"strings"
	"time"
)

func main() {
	cmd := ParseCmd()

	if cmd.helpFlag {
		flag.PrintDefaults()
		return
	}

	if cmd.versionFlag {
		fmt.Println("S文件下载转换工具 V1.0.0 版本")
		return
	}

	if cmd.parseType == 3 {
		downloadSFile(cmd)
		return
	}

	//
	if cmd.parseType == 4 {
		if isEmpty(cmd.inPath) {
			panic("文件输入目录不能为空!")
		}
		sfile.CheckOweFeeMinAcctDay(cmd.inPath)
		return
	}
	if cmd.parseType == 5 {
		if isEmpty(cmd.inPath) {
			panic("文件输入输出目录不能为空!")
		}
		sfile.CheckSFile(cmd.inPath, cmd.poolSize)
		return
	}

	if isEmpty(cmd.inPath) {
		panic("文件输入输出目录不能为空!")
	}
	if isEmpty(cmd.outPath) {
		panic("文件输入输出目录不能为空!")
	}
	if cmd.parseType == 2 && (isEmpty(cmd.oldCycle) || isEmpty(cmd.newCycle)) {
		panic("新老账期不能为空!")
	}
	//dir := "E:/work/Asiainfo/writeoff/membill/20210101/1/"
	//outDir := "E:/work/Asiainfo/writeoff/membill/20210101_new/1/"
	dir := cmd.inPath
	outDir := cmd.outPath
	if strings.Index(outDir, dir) > -1 {
		panic("输出目录不能是输入目录的子目录!")
	}
	repFiles(dir, outDir, cmd)
}

func downloadSFile(cmd *Cmd) {
	now := time.Now()
	if isEmpty(cmd.host) {
		panic("host 不能为空!")
	}
	if isEmpty(cmd.port) {
		panic("port 不能为空!")
	}
	if isEmpty(cmd.userName) {
		panic("userName 不能为空!")
	}
	if isEmpty(cmd.password) {
		//./get-uni-pswd.py FTP 10.254.78.249 ftp7311
		// /home/asset/sbin/get-uni-pswd.py FTP 10.254.78.249 ftp7311
		pwd := getPwd(cmd)
		cmd.password = pwd
		if isEmpty(cmd.password) {
			panic("password 不能为空!")
		}
	}
	if isEmpty(cmd.remotePath) {
		panic("remotePath 不能为空!")
	}
	if isEmpty(cmd.localPath) {
		panic("localPath 不能为空!")
	}
	ftp.Download(cmd.host, cmd.port, cmd.userName, cmd.password, cmd.remotePath, cmd.localPath, cmd.poolSize)
	log.Printf("下载耗时:%v", time.Since(now))
}

func isEmpty(str string) bool {
	return str == "" || len(str) <= 0
}

//将老系统S文件转换为新系统S文件
func repFiles(dir string, outDir string, cmd *Cmd) {
	readDir, err := ioutil.ReadDir(dir)
	if err != nil {
		return
	}
	for _, f := range readDir {
		name := f.Name()
		if cmd.parseType == 2 {
			name = strings.ReplaceAll(name, timeUtil.GetAcctDay(cmd.oldCycle), timeUtil.GetAcctDay(cmd.newCycle))
		}
		outFileName := outDir + "/" + name
		if f.IsDir() {
			repFiles(dir+"/"+f.Name(), outFileName, cmd)
		}
		//已经写过的,不再写了
		_, err := os.Stat(outFileName)
		if err == nil {
			continue
		}
		//排除total.log文件
		if strings.Index(name, ".") > -1 {
			continue
		}
		fmt.Println(name)
		file, err := ioutil.ReadFile(dir + "/" + f.Name())
		if err != nil {
			continue
		}
		s := string(file)
		if len(s) == 0 {
			continue
		}
		lines := strings.Split(s, "\n")
		newLines := make([]string, 0)
		for _, line := range lines {
			if len(line) == 0 {
				continue
			}
			newLine := ""
			switch cmd.parseType {
			case 2:
				//月份转换
				newLine = strings.ReplaceAll(strings.ReplaceAll(line, timeUtil.GetAcctDay(cmd.oldCycle), timeUtil.GetAcctDay(cmd.newCycle)), cmd.oldCycle, cmd.newCycle)
				break
			case 1:
			default:
				//新老转换
				//按逗号分割
				b := strings.Split(line, ",")
				//将第12个复制一份
				b = append(b[:11], append([]string{b[11]}, b[11:]...)...)
				newLine = strings.Join(b, ",")
			}
			newLines = append(newLines, newLine)

		}
		join := strings.Join(newLines, "\n")

		suffix := join[0 : len(join)-1]
		_, err = os.Stat(outDir)
		//目录不存在，创建目录
		if err != nil {
			err = os.MkdirAll(outDir, os.ModePerm)
			if err != nil {
				panic(err)
			}
		}
		//写文件
		err = ioutil.WriteFile(outFileName, []byte(suffix), os.ModePerm)
		if err != nil {
			panic(err)
		}
	}
}

func getPwd(flag *Cmd) string {
	cmd := exec.Command(flag.pwdShellPath, flag.pwdType, flag.host, flag.userName) //不加第一个第二个参数会报错

	//cmd.Stdout = os.Stdout // cmd.Stdout -> stdout  重定向到标准输出，逐行实时打印
	//cmd.Stderr = os.Stderr // cmd.Stderr -> stderr
	//也可以重定向文件 cmd.Stderr= fd (文件打开的描述符即可)
	stdout, _ := cmd.StdoutPipe() //创建输出管道
	defer stdout.Close()
	if err := cmd.Start(); err != nil {
		log.Fatalf("cmd.Start: %v", err)
	}

	fmt.Printf("命令执行参数:%v", cmd.Args) //查看当前执行命令

	cmdPid := cmd.Process.Pid //查看命令pid
	fmt.Println(cmdPid)
	result, _ := ioutil.ReadAll(stdout) // 读取输出结果
	resdata := strings.ReplaceAll(strings.ReplaceAll(string(result), "\n", ""), " ", "")
	/*var res int
	if err := cmd.Wait(); err != nil {
		if ex, ok := err.(*exec.ExitError); ok {
			fmt.Println("cmd exit status")
			res = ex.Sys().(syscall.WaitStatus).ExitStatus() //获取命令执行返回状态，相当于shell: echo $?
		}
	}
	fmt.Println(res)*/
	return resdata
}
